import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class ScreenCap implements ActionListener
{
	private JButton captureScreenButton;
	private JButton quitButton;
	private JFrame mainFrame;
	
	private ImageFrame imageFrame;
	private Robot robot;
	
	public ScreenCap()
	{
		mainFrame = new JFrame("ScreenCap");
		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainFrame.setLayout(new FlowLayout());
		mainFrame.setResizable(false);
		
		captureScreenButton = new JButton("Capture Screen!");
		captureScreenButton.addActionListener(this);
		mainFrame.add(captureScreenButton);
		
		quitButton = new JButton("Quit");
		quitButton.addActionListener(this);
		mainFrame.add(quitButton);
		
		try {
			robot = new Robot();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		imageFrame = new ImageFrame();
		
		mainFrame.pack();
		mainFrame.setVisible(true);
	}
	
	public static void main(String[] args)
	{
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(
							UIManager.getSystemLookAndFeelClassName());
				} catch (Exception e) {
					System.err.println("Error: Couldn't change look and feel!");
					System.exit(1);
				}
				
				new ScreenCap();
			}
		});
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == captureScreenButton) {
			mainFrame.setVisible(false);
			
			try {
				Thread.sleep(400);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
			imageFrame.loadImage(robot.createScreenCapture(new Rectangle(dim)));
			
			mainFrame.setVisible(true);
		} else if (e.getSource() == quitButton) {
			System.exit(0);
		}
	}
}